package com.h819.core.web.jquery;

import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: JavaObejctToJsonServlet.java
 * @Description: TODO(经过 struts2 json plugin 处理过的 json 对象，会多出转义字符"/"，不同的 jquery
 *               插件处理这个 json 对象时，会有很多问题。所以还是用 servlet 直接处理吧，不用 struts2 json
 *               plugin 插件要什么格式，就返回什么格式，不再动脑筋在修改源代码。)
 * @author H819
 * @date 2010-10-3
 * @version V1.0
 */

// 利用 firebug 查看插件需要的 json 格式
public class JavaObejctToJsonServlet extends HttpServlet {

	private Logger log = Logger.getLogger(JavaObejctToJsonServlet.class);

	// ===插件名称
	// 自动完成
	private String autocomplete = "autocomplete";
	// 级联 select
	private String relatedDependentSelects = "relatedDependentSelects";
	// ajax json select
	private String ajaxjsonselect = "ajaxjsonselect";

	private List<Map<String, String>> li = new ArrayList<Map<String, String>>();
	private Map<String, String> map;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String pluginname = (String) request.getParameter("pluginname");

		// 自动完成
		if (pluginname.equals(this.autocomplete)) {
			this.autocomplete(request, response);
		}
		// ajax json select
		if (pluginname.equals(this.ajaxjsonselect)) {

			this.ajaxJsonSelects(request, response);
		}

		// 级联菜单
		if (pluginname.equals(this.relatedDependentSelects)) {

			this.relatedDependentSelects(request, response);
		}

	}

	/**
	 * 自动完成
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void autocomplete(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		response.setContentType("text/html; charset=utf-8");

		PrintWriter out = response.getWriter();

		String q = (String) request.getParameter("q");

		li.clear();

		log.info("begin to prepare json");
		log.info("获得的参数是: " + q);

		map = new HashMap<String, String>();
		map.put("name", "jiang");
		map.put("to", "jiang@gmail.com");
		li.add(map);

		map = new HashMap<String, String>();
		map.put("name", "jianghui");
		map.put("to", "jianghui@gmail.com");
		li.add(map);

		map = new HashMap<String, String>();
		map.put("name", "jhui");
		map.put("to", "邮件地址jiang@gmail.com");
		li.add(map);
		// 将要返回的list对象进行json处理
		JSONArray jo = JSONArray.fromObject(li);

		log.info("json string in autocomplete : " + jo.toString());
		out.println(jo.toString());
		out.flush();
		out.close();

	}

	/**
	 * jquery ajax json select 填充演示
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void ajaxJsonSelects(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		response.setContentType("text/html; charset=utf-8");

		PrintWriter out = response.getWriter();

		li.clear();

		log.info("begin to prepare json");

		// 注意:
		// 每对 map 的 key ，名字需分别为 name 和 value
		// 否则 前台无法接收
		// 测试数据一：
		map = new HashMap<String, String>();
		map.put("name", "jiang");
		map.put("value", "jiang@gmail.com");
		li.add(map);
		// 测试数据二：
		map = new HashMap<String, String>();
		map.put("name", "jianghui");
		map.put("value", "jianghui@gmail.com");
		li.add(map);
		// 测试数据三：
		map = new HashMap<String, String>();
		map.put("name", "jhui");// 必须为name
		map.put("value", "邮件地址jiang@gmail.com");// 必须为 value
		li.add(map);

		// 将要返回的list对象进行json处理
		JSONArray jo = JSONArray.fromObject(li);

		log.info("json string : " + jo.toString());
		out.println(jo.toString());
		out.flush();
		out.close();
	}

	/**
	 * 级联菜单. 注意最终 json 字符串要进一步处理，去掉两边的分号
	 * 
	 * 如果数据是从数据库中获取的，获取 Connection 的代码需放在方法体内，因为执行该方法的时候，只生成一个实例
	 * 
	 * 反复调用，如果关闭了 Connection 就会无法获取连接。
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void relatedDependentSelects(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		response.setContentType("text/html; charset=utf-8");

		//Connection conn = MyDbUtils.getInstance().getConnectionMysql136();
		
		PrintWriter out = response.getWriter();

		li.clear();
		// 接收 jquery-related-selects_1.1 参数
		String stateID = (String) request.getParameter("stateID");
		String countyID = (String) request.getParameter("countyID");
		String townID = (String) request.getParameter("townID");

		String temp = "";

		//查询第二级
		if (stateID != null && countyID == null && townID == null) {

			log.info("stateID :" + stateID);
			map = new HashMap<String, String>();

			// map 结构说明
			// key 为 option 值,value 为显示名称
			// <option value="opiton value1">opiton name1</option>
			map.put("opiton value1", "opiton name1");
			map.put("opiton value2", "opiton name2");
			li.add(map);

			// 数据从数据库查询出来，写法
			// searchSql =
			// "select name,left(code,4) as scode from xukeclass where right(code,2) ='00' and right(code,4) !='0000' and code like '"
			// + oneclass + "%'";
			// log.info("查询二级分类：searchSql :" + searchSql);
			// searchResult = runner.query(conn, searchSql,
			// new MapListHandler());
			//		
			// map = new HashMap<String, String>();
			// for (Map m : searchResult) {//单条记录
			// String name = "";
			// String value = "";
			// for (Iterator it = m.entrySet().iterator(); it.hasNext();) {
			//		
			// Map.Entry entry = (Map.Entry) it.next();
			// if (entry.getKey().toString().equals("scode"))
			// value = entry.getValue().toString();
			//
			// if (entry.getKey().toString().equals("name"))
			// name = entry.getValue().toString();
			// }
			//			
			// if(!name.equals("")&&!value.equals(""))
			// {
			// //map 结构说明
			// // key 为 option 值,value 为显示名称
			// map.put(value, name);
			// }
			// }
			//		
			// li.add(map);

		} else if (stateID != null && countyID != null && townID == null) {//查询第三级

			log.info("countyID :" + countyID);

			map = new HashMap<String, String>();
			map.put("county1", "county1");
			map.put("county2", "county2");
			li.add(map);

		} else if (stateID != null && countyID != null && townID != null) { //查询第四级

			log.info("townID :" + townID);

			map = new HashMap<String, String>();
			map.put("town1", "town1");
			map.put("town2", "town2");
			li.add(map);

		} else {
			out.println("{}");
		}

		// 注意去掉两边的分号。
		temp = JSONArray.fromObject(li).toString();
		temp = StringUtils.removeStart(temp, "[");
		temp = StringUtils.removeEnd(temp, "]");
		log.info("json string in relatedDependentSelects : " + temp);
		out.println(temp);
		out.flush();
		out.close();
	}

	public JavaObejctToJsonServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	public void init() throws ServletException {
		// Put your code here
	}
}
